package com.wenlin.myproduction.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import org.greenrobot.eventbus.EventBus;

import java.lang.reflect.Field;

import butterknife.ButterKnife;
import butterknife.Unbinder;

public abstract class BaseFragment extends Fragment {
    protected View mContentView;
    Unbinder mUnbinder;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mContentView == null) {
            mContentView = inflater.inflate(getLayoutRes(), container, false);
        }
        return mContentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mUnbinder = ButterKnife.bind(this, getView());
    }

    public View getContentView() {
        return mContentView;
    }

    @LayoutRes
    protected abstract int getLayoutRes();

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        try {
            if (mContentView != null && mContentView.getParent() instanceof ViewGroup) {
                ((ViewGroup) mContentView.getParent()).removeView(mContentView);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDestroy() {
        //这里统一加一个处理，子类中使用EventBus的时候只要register即可，无需unregister
        if (EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        if (mUnbinder != null) {
            mUnbinder.unbind();
        }
        if (mContentView instanceof ViewGroup) {
            ((ViewGroup) mContentView).removeAllViewsInLayout();
        }
        mContentView = null;
        super.onDestroy();
    }

    /**
     * 创建多个MainActivity时导致共用一个Fragment，在MainActivity执行oncreate统一回收
     */
    public void onRecycle() {

    }


}
